package com.meihua.baoleyi.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.adapters.KnowledgeAdapter;
import com.meihua.baoleyi.base.BaseFragment;
import com.meihua.baoleyi.bean.knowledgeBean;
import com.meihua.baoleyi.utils.MD5;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.utils.UrlContants;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liming on 2017/10/16
 * 百科知识界面
 */
public class BaikeFragment extends BaseFragment {

    @Bind(R.id.common_no_data_layout)
    LinearLayout commonNoDataLayout;

    private Context mcontext;
    private XRecyclerView mLv_knowledge;
    private KnowledgeAdapter mKnowledgeAdapter;

    private int page = 1;
    private int count_page = 10;
    private int times = 0;
    private boolean isRefreshing = true;

    private List<knowledgeBean> knowledgeList = new ArrayList<>();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mcontext = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.baike_fragment, container, false);
        ButterKnife.bind(this, view);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mLv_knowledge = (XRecyclerView) view.findViewById(R.id.lv_baike);
        mKnowledgeAdapter = new KnowledgeAdapter(mcontext, knowledgeList);
        mLv_knowledge.setAdapter(mKnowledgeAdapter);

        mLv_knowledge.setLayoutManager(new LinearLayoutManager(mcontext, LinearLayoutManager.VERTICAL, false));
        mLv_knowledge.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mLv_knowledge.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate); //BallRotate 三个点文字显示正在加载
        mLv_knowledge.setArrowImageView(R.drawable.iconfont_downgrey);

        //加载更多
        mLv_knowledge.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                isRefreshing = true;
                BaikeKnowlede();
            }

            @Override
            public void onLoadMore() {
                page++;
                isRefreshing = false;
                BaikeKnowlede();
            }
        });
        BaikeKnowlede();
    }

    /**
     * 获取百科知识
     */
    private void BaikeKnowlede() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        String token = app.getToken().toString();
        String sign_none = "page=" + page + "" + "&timestamp=" + str + "&token=" + token;
        String sign_yes = MD5.getMessageDigest(sign_none.toString().getBytes()).toUpperCase();
        OkGo.get(UrlContants.HOST + "api/baike/index?page=" + page + "" + "&timestamp=" + str + "&token=" + token + "&sign=" + sign_yes)
                .tag(this)
                .params("token", token)//token
                .params("timestamp", str)//时间戳
                .params("page", page + "")//分页
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                if (jsonObject.optString("code").equals("200")) {
                                    //请求成功
                                    String date = jsonObject.optString("date");
                                    List<knowledgeBean> goodsimageList = JSONArray.parseArray(date, knowledgeBean.class);
                                    if (page == 1) {
                                        knowledgeList.clear();
                                    }
                                    knowledgeList.addAll(goodsimageList);
                                    if (knowledgeList.size() <= 0 && isRefreshing) {
                                        if (commonNoDataLayout != null) {
                                            commonNoDataLayout.setVisibility(View.VISIBLE);
                                        }
                                    } else {
                                        if (commonNoDataLayout != null) {
                                            commonNoDataLayout.setVisibility(View.GONE);
                                        }
                                    }
                                    mKnowledgeAdapter.notifyDataSetChanged();
                                    if (isRefreshing) {
                                        mLv_knowledge.refreshComplete();
                                    } else {
                                        mLv_knowledge.loadMoreComplete();
                                    }
                                } else {
                                    ToastUtil.show(getActivity(), jsonObject.optString("msg"));
                                    if (commonNoDataLayout != null && isRefreshing) {
                                        commonNoDataLayout.setVisibility(View.VISIBLE);
                                    }
                                    if (isRefreshing) {
                                        mLv_knowledge.refreshComplete();
                                    } else {
                                        mLv_knowledge.loadMoreComplete();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(mcontext,"服务器异常",Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        ToastUtil.showShort(mcontext, e.toString());
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 点击重试
     */
    @OnClick(R.id.common_click_retry_tv)
    public void onViewClicked() {
        mLv_knowledge.refresh();
    }
}
